package org.example;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class QTreeRender {
    private Graphics2D g = null;
    public void renderQuadTree(QuadTree root,
                               int size,
                               String outputPath,
                               ArrayList<Point> routes) {
        var img = new BufferedImage(size, size, BufferedImage.TYPE_INT_BGR);
        g = img.createGraphics();
        var at = new AffineTransform();
        // 按y轴翻转后上移512，效果等于图像翻转。
        at.concatenate(AffineTransform.getScaleInstance(1,-1));
        at.concatenate(AffineTransform.getTranslateInstance(0, -512));
        g.transform(at);
        render(root);
        // test!
        //    g.setColor(Color.green);
        //    g.drawLine(64, 64, 32, 160);
        //    g.drawRect(0, 128 ,64 ,64);
        if (!routes.isEmpty()) {
            g.setColor(Color.blue);
            var pathIterator = routes.iterator();
            var prePoint = pathIterator.next();
            while (pathIterator.hasNext()) {
                var currentPoint = pathIterator.next();
                // 绘制线段
                g.drawLine(prePoint.x, prePoint.y, currentPoint.x, currentPoint.y);
                prePoint = currentPoint;
            }
        }
        g.dispose();
        try {
            ImageIO.write(img, "png", new File(outputPath));
        } catch (IOException e) {
            System.out.println("在渲染四叉树到png时发生了错误：" + e);
        }
    }

    public void render(QuadTree node) {
        if (node.getClass() == Leaf.class) {
            Leaf l = (Leaf)node;
            g.setColor(l.isObstacle ? Color.black : Color.white);
            g.fillRect(l.bound.x, l.bound.y, l.bound.size, l.bound.size);
            g.setColor(Color.lightGray);
            g.drawRect(l.bound.x, l.bound.y, l.bound.size, l.bound.size);
            g.setColor(Color.green);
            var centerPoints = new ArrayList<Point>();
            l.neighbors.forEach( lf-> centerPoints.add(new Point(lf.bound.x + lf.bound.size / 2, lf.bound.y + lf.bound.size/2)));
            var thisCenter = new Point(l.bound.x + l.bound.size / 2, l.bound.y + l.bound.size/2);
            centerPoints.forEach(a->g.drawLine(thisCenter.x, thisCenter.y, a.x, a.y));
        }
        else if (node.getClass() == TreeNode.class) {
            TreeNode n = (TreeNode)node;
            // 子节点顺序是: 左上、右上、左下、右下
            render(n.nw);
            render(n.ne);
            render(n.sw);
            render(n.se);
        }
    }

}
